//
//  common.swift
//  Phone
//
//  Created by redjun Z on 2019/1/30.
//  Copyright © 2019 network.xiaozhang.com. All rights reserved.
//

import Foundation
import UIKit

var phoneNumberArray = [String]()

var userImgArray = [String]()

//MARK:  延迟执行代码
public func delay(_ seconds: UInt64, task: @escaping () -> Void) {
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(seconds * NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: task)
}

/// 保存手机号
///
/// - Parameter number: 手机号
func savePhone(number: String) {
    if UserDefaults.standard.object(forKey: "phoneNumberList") != nil {
        phoneNumberArray = UserDefaults.standard.object(forKey: "phoneNumberList") as! [String]
    }
    phoneNumberArray.append(number)
    UserDefaults.standard.set(phoneNumberArray, forKey: "phoneNumberList")
    UserDefaults.standard.synchronize()
}
// 读取本地手机号列表
func redLocationPhoneNumber() -> [String]? {
    if UserDefaults.standard.object(forKey: "phoneNumberList") != nil {
        phoneNumberArray = UserDefaults.standard.object(forKey: "phoneNumberList") as! [String]
    }
    return phoneNumberArray
}

//修改手机号
func updateUseriphone(newNumber: String,originalNumber: String) {
    var suoyin: Int?
    guard var list = redLocationPhoneNumber() else {return}
    for (index , item) in list.enumerated() {
        if item == originalNumber {
            suoyin = index
            print("旧手机号\(item) 修改为新手机号\(newNumber)")
        }
    }
    
    if let index = suoyin {
        list[index] = newNumber
        userlistUpdate(list: list)
        updateFileName(newNumber: newNumber, originalNumber: originalNumber)
    } else {
        print("手机号修改失败 ❌")
    }
}
//更新本地 手机号
func userlistUpdate(list: [String]){
    UserDefaults.standard.set(list, forKey: "phoneNumberList")
    UserDefaults.standard.synchronize()
}
//MARK: 获取通讯录 头像 保存路径
func getUserAddressBookPath(path: String? = nil) -> String {
    if let path = path {
        return NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first! + "/" + path
    }
    return NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
}

//MARK: 保存图片到本地
func baocunphotoLocation(data: Data?,img: UIImage?,nameImg: String)-> Bool{
    let fileManager = FileManager.default
    
    var cachePath = getUserAddressBookPath(path: "AddressBookList")
    cachePath = cachePath + "/" + nameImg
    print("保存路径 \(cachePath)")
    
    //    路径不存在 创建路径
    if !fileManager.fileExists(atPath: cachePath) {
        //withIntermediateDirectories为ture表示路径中间如果有不存在的文件夹都会创建
        try! fileManager.createDirectory(atPath: getUserAddressBookPath(path: "AddressBookList"),
                                         withIntermediateDirectories: true, attributes: nil)
    }
    
    if let data = data {
        fileManager.createFile(atPath: cachePath, contents: data, attributes: nil)
    } else if let image = img {
        let imgdata = image.zz_normalizedImage().jpegData(compressionQuality: 0.9)
        fileManager.createFile(atPath: cachePath, contents: imgdata, attributes: nil)
    } else {
        return false
    }
    return true
}

//MARK: 根据文件名 查找目录下指定文件
func locationfileiscache(filepath: String?,fileName: String, complate:(_ callback: String?)->Void) {
    var cachePath = ""
    if let path = filepath {
        cachePath = path
    } else {
        cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
    }
    // 打印路径,需要测试的可以往这个路径下放东西
    var path = ""
    //    cachePath = cachePath + "/"
    // 取出文件夹下所有文件数组
    if let files = try? FileManager.default.subpathsOfDirectory(atPath: cachePath + "/" ){
        // 快速枚举取出所有文件名
        for p in files {
            print("\(p) 我要找\(fileName)")
            if p.contains(fileName) {
                path = cachePath.appendingFormat("/\(p)")
                return complate(path)
            }
        }
    }
    complate(nil)
}

//MARK:-- file 重命名
func updateFileName(newNumber: String,originalNumber: String) {
    locationfileiscache(filepath: getUserAddressBookPath(), fileName: "\(originalNumber).jpg") { (path) in
        if let lujing = path {
            let moveManager2 = FileManager.default
            
            let moveFromUrl2 = URL(fileURLWithPath: lujing)
            var moveToUrl2: URL?
            //            if lujing.contains("AddressBookList") {
            //                    moveToUrl2 = URL(fileURLWithPath: getUserAddressBookPath()).appendingPathComponent("\(newNumber).jpg")
            //            } else {
            moveToUrl2 = URL(fileURLWithPath: getUserAddressBookPath(path: "AddressBookList")).appendingPathComponent("\(newNumber).jpg")
            //            }
            
            // 移动srcUrl中的文件（test.txt）到toUrl中（copyed.txt）
            try? moveManager2.moveItem(at: moveFromUrl2, to: moveToUrl2!)
            
        }
    }
}

//MARK: -- 科学记数 转 double字符串
func formartScientificNotationWithString(str: String) -> String {
    let num = CFStringGetDoubleValue(str as CFString)
    if num < 1 {
        return String(num)
    }
    let formatter = NumberFormatter()
    formatter.numberStyle = NumberFormatter.Style.decimal
    return RemoveSpecialCharacter(formatter.string(from: NSNumber(value: num)) ?? "")
}

//MARK:  字符串过滤
func RemoveSpecialCharacter(_ str: String) -> String {
    let range = str.rangeOfCharacter(from: CharacterSet(charactersIn: "-,？、% ~￥#&<>《》()[]{}【】^@/￡¤|§¨「」『』￠￢￣~@#&*（）——+|《》$_€"))
    if range != nil {
        return RemoveSpecialCharacter(str.replacingCharacters(in: range!, with: ""))
    }
    return str
}

//func readFile(){
//    let manager = FileManager.default
//    let urlsForDocDirectory = manager.urls(for: FileManager.SearchPathDirectory.documentDirectory, in:FileManager.SearchPathDomainMask.userDomainMask)
//    let docPath:NSURL = urlsForDocDirectory[0] as NSURL
//    let file = docPath.appendingPathComponent("test.txt")
//
//    let hhsh = "file:///var/mobile/Media/DCIM/100APPLE/IMG_0006.JPG"
//    //方法1
//    let readHandler1 = FileHandle(forReadingAtPath: hhsh)
//    let data1 = readHandler1?.readDataToEndOfFile()
//    print(UIImage(data: data1))
//
//    let readHandler = try! FileHandle(forReadingFrom:file)
//    let data = readHandler.readDataToEndOfFile()
//    let readString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
//    print("文件内容: \(readString)")
//
//    //方法2
//    let data1 = manager.contents(atPath: (file?.path)!)
//    let readString1 = NSString(data: data1!, encoding: String.Encoding.utf8.rawValue)
//    print("文件内容: \(readString1)")
//}

